package com.threeti.mecool.core.application;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.basicdata.biz.ChannelSync;
import com.threeti.mecool.core.domain.model.project.Project;
import com.threeti.mecool.core.domain.model.project.ProjectStore;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.core.infrastructure.persistence.project.ProjectStoreRepository;

@Service
public class MemoServiceImpl implements MemoService {
  @Autowired
  private ProjectService projService;
  
  @Autowired
  private ProjectStoreRepository projStoreRepo;
  
  @Autowired
  private UserRepository userRepo;

  @Override
  public Set<ChannelSync> findChannelsSharedByProjectsOf(String userLoginName) {
    User user = userRepo.findByloginName(userLoginName);
    if (user == null) return Collections.emptySet();
    
    List<Project> projects = projService.findByUserOwn(user);
    
    if (CollectionUtils.isEmpty(projects)) return Collections.emptySet();
    
    List<ProjectStore> projStoresWithDuplicateDisplayName = projStoreRepo.findByProjectIn(projects);
    
    Set<ChannelSync> channels = new LinkedHashSet<ChannelSync>();
    
    for (ProjectStore projectStore : projStoresWithDuplicateDisplayName) {
      channels.add(projectStore.getChannel());
    }    
    return channels;
  }

}
